package com.example.demo11.controller;

import com.example.demo11.domian.NeoProperties;
import org.apache.catalina.filters.RemoteIpFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Configuration
public class WebConfigure {

    @Bean
    public RemoteIpFilter remoteIpFilter(){
        return new RemoteIpFilter();
    }

    @Bean
    public FilterRegistrationBean testFilterRegistration(){
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(new MyFiler());
        registration.addUrlPatterns("/*");
        registration.addInitParameter("paramName", "paramValue");
        registration.setName("MyFilter");
        registration.setOrder(1);
        return registration;
    }

    //触发filter 配置到web service filter
    public class MyFiler implements Filter {

        @Override
        public void init(FilterConfig filterConfig) throws ServletException {
            //过滤器被创建时候需要初始化
            System.out.println("myfilter create");
        }

        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
            //过滤的指数要步骤 (每次route 请求向经过filter 然后到 servlet)

            NeoProperties neoProperties = new NeoProperties();
            HttpServletRequest request = (HttpServletRequest) servletRequest;
            System.out.println("this is myFilter url" + request.getRequestURL());
            filterChain.doFilter(servletRequest,servletResponse);
        }

        @Override
        public void destroy() {
            //消耗的时候执行的方法
            System.out.println("myfilter end");
        }
    }
}
